package com.example.demo.config;




import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;


// 统一异常处理
//@ControllerAdvice // 给类加上该注解
//@ResponseBody //返回是一个JSON格式 不是静态页面数据

//什么两个注解我们可以统一写成
@RestControllerAdvice
public class MyExceptionAdvice {

    // 记得加异常注解
    @ExceptionHandler(ArithmeticException.class)
    public HashMap<String, Object> arithmeticExceptionAdvice(ArithmeticException e) {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("state", -1);
        hashMap.put("data", null);
        hashMap.put("msg", "算数异常" + e.getMessage());
        return hashMap;
    }



//    统一异常
    @ExceptionHandler(Exception.class)
    public HashMap<String, Object> exceptionAdvice(Exception e) {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("state", -1);
        hashMap.put("data", null);
        hashMap.put("msg", "异常" + e.getMessage());
        return hashMap;
    }
}
